package com.shuiyun.demo.utils;

import cn.hutool.json.JSONUtil;
import com.shuiyun.demo.entity.JobInfoAware;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author tianye
 */
@Component
public class ScheduleUtils {

    private final static String JOB_NAME = "TASK_";

    public final static String JOB_PARAM_KEY = "JOB_PARAM";

    @Autowired
    private Scheduler scheduler;


    /**
     * 获取触发器key
     */
    private static TriggerKey getTriggerKey(String jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(String jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    private CronTrigger getCronTrigger(String jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException("获取定时任务CronTrigger出现异常", e);
        }
    }

    private SimpleTrigger getSimpleTrigger(String jobId) {
        try {
            return (SimpleTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException("获取定时任务SimpleTrigger出现异常", e);
        }
    }

    /**
     * 创建定时任务
     */
    public void createScheduleJob(JobInfoAware jobInfo, Class<? extends Job> jobClass) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobInfo.getJobId())).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getJobCron())
                    .withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(getTriggerKey(jobInfo.getJobId()))
                    .withSchedule(scheduleBuilder)
                    .build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JOB_PARAM_KEY, JSONUtil.toJsonStr(jobInfo.getJobParams()));
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务失败", e);
        }
    }

    /**
     * 创建一次性定时任务
     */
    public void createOnceScheduleJob(JobInfoAware jobInfo, Class<? extends Job> jobClass) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobInfo.getJobId())).build();

            //表达式调度构建器
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0);

            //按新的executeTime构建一个新的trigger
            SimpleTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(getTriggerKey(jobInfo.getJobId()))
                    .startAt(jobInfo.getExecuteTime())
                    .withSchedule(scheduleBuilder)
                    .build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JOB_PARAM_KEY, JSONUtil.toJsonStr(jobInfo.getJobParams()));
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务失败", e);
        }
    }

    /**
     * 更新定时任务
     */
    public void updateScheduleJob(JobInfoAware jobInfo) {
        try {
            TriggerKey triggerKey = getTriggerKey(jobInfo.getJobId());

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getJobCron())
                    .withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(jobInfo.getJobId());

            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            //参数
            trigger.getJobDataMap().put(JOB_PARAM_KEY, JSONUtil.toJsonStr(jobInfo.getJobParams()));

            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("更新定时任务失败", e);
        }
    }

    /**
     * 更新定时任务
     */
    public void updateOnceScheduleJob(JobInfoAware jobInfo) {
        try {
            TriggerKey triggerKey = getTriggerKey(jobInfo.getJobId());

            //表达式调度构建器
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0);

            SimpleTrigger trigger = getSimpleTrigger(jobInfo.getJobId());

            //按新的executeTime表达式重新构建trigger
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .startAt(jobInfo.getExecuteTime())
                    .withSchedule(scheduleBuilder)
                    .build();

            //参数
            trigger.getJobDataMap().put(JOB_PARAM_KEY, JSONUtil.toJsonStr(jobInfo.getJobParams()));

            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("更新定时任务失败", e);
        }
    }

    /**
     * 立即执行任务
     */
    public void run(JobInfoAware jobInfo) {
        try {
            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JOB_PARAM_KEY, JSONUtil.toJsonStr(jobInfo.getJobParams()));

            scheduler.triggerJob(getJobKey(jobInfo.getJobId()), dataMap);
        } catch (SchedulerException e) {
            throw new RuntimeException("立即执行定时任务失败", e);
        }
    }

    /**
     * 暂停任务
     */
    public void pauseJob(String jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务失败", e);
        }
    }

    /**
     * 恢复任务
     */
    public void resumeJob(String jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务失败", e);
        }
    }

    /**
     * 删除定时任务
     */
    public void deleteScheduleJob(String jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RuntimeException("删除定时任务失败", e);
        }
    }

}
